package com.sky.aspect;

import com.sky.context.BaseContext;
import com.sky.enumeration.AutoFill;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    /**
     * 切入点
     */
    @Pointcut("@annotation(com.sky.enumeration.AutoFill)")
    public void autoFill() {

    }

    @Before("autoFill()")
    public void before(JoinPoint joinPoint) {
        //获取到被拦截的方法的数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();
        //获取到被拦截的方法的参数
        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || args == null) {
            return;
        }
        Object object = args[0];
        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();
        if (operationType == OperationType.INSERT) {
            try {
                object.getClass().getMethod("setCreateTime", LocalDateTime.class).invoke(object, now);
                object.getClass().getMethod("setUpdateTime", LocalDateTime.class).invoke(object, now);
                object.getClass().getMethod("setCreateUser", Long.class).invoke(object, id);
                object.getClass().getMethod("setUpdateUser", Long.class).invoke(object, id);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        } else if (operationType == OperationType.UPDATE) {
            try {
                object.getClass().getMethod("setUpdateTime", LocalDateTime.class).invoke(object, now);
                object.getClass().getMethod("setUpdateUser", Long.class).invoke(object, id);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);

            }
        }
    }
}
